package com.rayboo.web.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 
 * WebErrorController
 * 
 * @author ray
 * @date 2016年9月8日 下午8:03:45
 *
 */
@Controller
public class WebErrorController implements ErrorController {
    @Autowired
    private ErrorAttributes errorAttributes;

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		model.addAttribute("title", ((HttpServletResponse) response).getStatus());

        Map<String, Object> errorAttributes = getErrorAttributes(request, false);
        Object errorMsg = (errorAttributes.get("message") != null) ? errorAttributes.get("message") : errorAttributes.get("error");
        model.addAttribute("description", errorMsg);

        return "error";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
    }
}